package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService{

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static{
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    private static final ExecutorService SECKILL_EXECUTOR = Executors.newSingleThreadExecutor();


    @PostConstruct
    private void init(){
        SECKILL_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private IVoucherOrderService proxy ;


    private class VoucherOrderHandler implements Runnable{
//        获取消息队列里的东西，顺便判断消息获取是否成功

//        判断消息获取是否成功

//        如果获取失败，说明没有消息，继续下一次循环

//        如果获取成功，可以下单，然后可以ack确认
        String queueName = "stream.orders";

        @Override
        public void run() {
            while(true){
                try{
                    List<MapRecord<String, Object, Object>> voucherOrder = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    if(voucherOrder == null || voucherOrder.isEmpty()){
                        continue;
                    }
                    MapRecord<String, Object, Object> record = voucherOrder.get(0);
                    Map<Object, Object> value = record.getValue();

                    VoucherOrder voucher =  BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

//                    如果获取成功，可以下单
                    handleVoucherOrder(voucher);
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());


                } catch (Exception e) {
                    log.error("出现订单异常" + e.getMessage());
                    try {
                        handlePendingList();
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
                }
            }
            private void handlePendingList() throws InterruptedException {
                while(true){
                    try{
                        List<MapRecord<String, Object, Object>> voucherOrder = stringRedisTemplate.opsForStream().read(
                                Consumer.from("g1", "c1"),
                                StreamReadOptions.empty().count(1),
                                StreamOffset.create(queueName, ReadOffset.from("0"))
                        );
                        if(voucherOrder == null || voucherOrder.isEmpty()){
                            break;
                        }
                        MapRecord<String, Object, Object> record = voucherOrder.get(0);
                        Map<Object, Object> value = record.getValue();

                        VoucherOrder voucher =  BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
//                    如果获取成功，可以下单

                        stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());


                    } catch (Exception e) {
                        log.error("出现订单异常,处理pendingList异常");
                        Thread.sleep(50);
                    }
                }


            }
        }





//    private class VoucherOrderHandler implements Runnable{
//        @Override
//        public void run() {
//            while(true){
////                获取队列中的信息
//                try {
//                    VoucherOrder voucherOrder =  orderTasks.take();
//                    handleVoucherOrder(voucherOrder);
//
//                } catch (InterruptedException e) {
//                    log.error("出现订单异常");
//                }
//            }
//        }
//    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userID = voucherOrder.getId();
        String lock = "lock:order:" + userID;
        RLock rlock = redissonClient.getLock(lock);
        boolean isLocked = rlock.tryLock();

        if(!isLocked){
            log.error("获取锁失败，出现用户重复下单");
        }

        try {
            proxy.createVoucherOrder(voucherOrder);
        } catch (IllegalStateException e) {
            throw new RuntimeException(e);
        } finally {
//            simpleRedisLock.unLock();
            rlock.unlock();
        }

    }

//    使用stream消息队列进行的队列进行下单
    @Override
    public Result seckillVoucher(Long voucherId) throws InterruptedException {
        Long userId = UserHolder.getUser().getId();
        Long order = redisIdWorker.nextrId("order");

        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(order)
        );
        int r = result.intValue();

        if(r == 1){
            return Result.fail("库存不足");
        }

        if(r == 2){
            return Result.fail("用户已经购买过，请勿重复下单");
        }

//        VoucherOrder voucherOrder = new VoucherOrder();
//
//        voucherOrder.setId(order);
//        voucherOrder.setUserId(userId);
//        voucherOrder.setVoucherId(voucherId);
//
////        创建一个阻塞队列，并将这个order传入给阻塞队列
//
//        orderTasks.add(voucherOrder);
//
        proxy = (IVoucherOrderService)AopContext.currentProxy();

        return Result.ok(order);
    }


//    @Override
//    public Result seckillVoucher(Long voucherId) throws InterruptedException {
//        Long userId = UserHolder.getUser().getId();
//        Long order = redisIdWorker.nextrId("order");
//
//        Long result = stringRedisTemplate.execute(
//                    SECKILL_SCRIPT,
//                    Collections.emptyList(),
//                    voucherId.toString(),
//                    userId.toString(),
//                    String.valueOf(order)
//                );
//        int r = result.intValue();
//
//        if(r == 1){
//            return Result.fail("库存不足");
//        }
//
//        if(r == 2){
//            return Result.fail("用户已经购买过，请勿重复下单");
//        }
//
//        VoucherOrder voucherOrder = new VoucherOrder();
//
//        voucherOrder.setId(order);
//        voucherOrder.setUserId(userId);
//        voucherOrder.setVoucherId(voucherId);
//
////        创建一个阻塞队列，并将这个order传入给阻塞队列
//
//        orderTasks.add(voucherOrder);
//
//        proxy = (IVoucherOrderService)AopContext.currentProxy();
//
//        return Result.ok(order);
//    }



//    @Override
//    public Result seckillVoucher(Long voucherId) throws InterruptedException {
////        1.查询优惠券信息。
//
////        2.判断当前时间是否在优惠券秒杀时间内
//
////        2.1 是则判断库存是否充足
//
////        2.2 充足就库存-1，并且创建订单
//
////        3.不充足返回异常
//
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//
//        if(seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
//            return Result.fail("秒杀尚未开始");
//        }
//
//        if(seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
//            return Result.fail("秒杀已经结束");
//        }
//
//        if(seckillVoucher.getStock() < 1){
//            return Result.fail("优惠券库存不足");
//        }
//
//
//        Long userID = UserHolder.getUser().getId();
//
////        尝试创建锁对象，然后通过对象加锁
//        String lock = "lock:order:" + userID;
//
//        RLock rlock = redissonClient.getLock(lock);
//        Boolean isLocked = rlock.tryLock();
//
//
//
////        使用传统方式redis加锁
////        SimpleRedisLock simpleRedisLock = new SimpleRedisLock(lock, stringRedisTemplate);
////
//////        synchronized (userID.toString().intern()){
////        Boolean isLocked = simpleRedisLock.tryLock(1200L);
//
//        if(!isLocked){
//            return Result.fail("不允许重复下单");
//        }
//
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService)AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId, userID);
//        } catch (IllegalStateException e) {
//            throw new RuntimeException(e);
//        } finally {
////            simpleRedisLock.unLock();
//            rlock.unlock();
//        }
//    }

    @Transactional(rollbackFor = Exception.class)
    public Result createVoucherOrder(Long voucherId, Long userID){
        //        加入判断一人一单，从voucher_order表中判断用户存不存在

            int count = query().eq("user_id",userID).eq("voucher_id",voucherId).count();
            if(count > 0){
                return Result.fail("一个用户仅能购买一单");
            }

//        扣库存
            boolean result = seckillVoucherService.update()
                    .setSql("stock = stock - 1")
                    .gt("stock", 0)
                    .eq("voucher_id",voucherId).update();

            if(!result){
                return Result.fail("优惠券库存不足");
            }

//        创建订单
            VoucherOrder voucherOrder = new VoucherOrder();

            Long order = redisIdWorker.nextrId("order");
            voucherOrder.setId(order);

            voucherOrder.setUserId(userID);
            voucherOrder.setVoucherId(voucherId);

            save(voucherOrder);

            return Result.ok(order);
        }

    @Override
    public void createVoucherOrder(VoucherOrder voucherOrder) {

        //        加入判断一人一单，从voucher_order表中判断用户存不存在
        Long userID = voucherOrder.getId();
        Long voucherId =voucherOrder.getVoucherId();
        int count = query().eq("user_id",userID).eq("voucher_id",voucherId).count();
        if(count > 0){
            log.error("一个用户仅能购买一单");
            return;
        }

//        扣库存
        boolean result = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .gt("stock", 0)
                .eq("voucher_id",voucherId).update();

        if(!result){
            log.error("优惠券库存不足");
            return;
        }
        save(voucherOrder);
    }
//创建一个阻塞队列



}
